#!/usr/bin/env python
#coding=utf-8

#******************************************
#This file for XCMD, created by OpenThings.
#Using this to automate the test procedure.
#Author: openthings@163.com. copyright&GPL V2.
#Last modified 2014-11-13.
#******************************************

print("  ==================================================")
print("  * X   X            CCCC   M     M  DDDDDD        *")
print("  *  X X            C       MM   MM   D    D       *")
print("  *   X   >>>>>>>>  C       M M M M   D    D       *")
print("  *  X X            C       M  M  M   D    D       *")
print("  * X   X            CCCC   M     M  DDDDDD        *")
print("  *------------------------------------------------*")
print("  *    Welcome to xConsole--[TCP] via WiFi!        *")
print("  *      For XCMD based ESP8266 SoC.               *")
print("  *     By openthings@163.com. 2014-10.            *")
print("  *------------------------------------------------*")
print("  *     通过网络控制台，远程执行@CMD指令集。       *")
print("  ==================================================")

#============================================
import sys
import threading
from socket import *
from time import *

import pynmea2

#import xcmd_xcon.xc_help
#import xlua_xcon.xc_help

#============================================
global gpsfile
global gpsfilename
gpsfilename = "gpslog_BD.txt"

#HOST = '192.168.199.202'
#HOST = '127.0.0.1'
#HOST = '192.168.1.4'
HOST = '192.168.1.9'
#HOST = '192.168.4.1'
#HOST = '192.168.199.236'
#HOST = '192.168.199.146'
#HOST = '192.168.199.192'

PORT = 8080
#PORT = 8268

ADDR = (HOST, PORT) 
addr = (HOST, PORT) 
IS_RUN = 1

print "   Create Client to TCP server..."
tcpClientSock = socket(AF_INET,SOCK_STREAM)
tcpClientSock.connect(ADDR) 

print "   Using TCP at: HOST-",HOST,",PORT-",PORT
print("   \"$\" for HOST, \"@\" for REMOTE,\"EXIT\" for exit. ")
print("  *================================================*")


#============================================
#GPS的累积法误差消除模型与网络化广域差分系统。
global gcount
global gtotal_lat,gtotal_lon
global lat1,lon1
gcount = 0
gtotal_lat = 0
gtotal_lon = 0
lat1 = 0
lon1 = 0

#============================================
def gpscenter(lat_sec,lon_sec):
	global gcount
	global gtotal_lat,gtotal_lon
	global lat1,lon1
	
	if gcount == 0:
		gtotal_lat = lat_sec
		gtotal_lon = lon_sec
		gcount = 1
	else:
		gtotal_lat = gtotal_lat + lat_sec
		gtotal_lon = gtotal_lon + lon_sec
		gcount = gcount + 1
	lat2 = gtotal_lat/gcount
	lon2 = gtotal_lon/gcount

	print "+++C=%d, T=%07.4f, V=[%07.4f], D=[%07.4f],DV=[%07.4f]"%(gcount,gtotal_lat,lat2,lat2-lat_sec,lat2-lat1)
	print "+++C=%d, T=%07.4f, V=[%07.4f], D=[%07.4f],DV=[%07.4f]"%(gcount,gtotal_lon,lon2,lon2-lon_sec,lon2-lon1)
	lat1 = lat2
	lon1 = lon2

def gpscenterx(msg):
	global gpsfile
	global gcount
	global gtotal_lat,gtotal_lon
	global lat1,lon1
	lat = msg.latitude
	lon = msg.longitude
	if gcount == 0:
		gtotal_lat = lat
		gtotal_lon = lon
		gcount = 1
	else:
		gtotal_lat = gtotal_lat + lat
		gtotal_lon = gtotal_lon + lon
		gcount = gcount + 1
	lat2 = gtotal_lat/gcount
	lon2 = gtotal_lon/gcount

	print "+++C=%d, T=%12.2f, V=[%12.8f], D=[%12.8f],DV=[%12.8f]"%(gcount,gtotal_lat,lat2,lat2-lat,lat2-lat1)
	print "+++C=%d, T=%12.2f, V=[%12.8f], D=[%12.8f],DV=[%12.8f]"%(gcount,gtotal_lon,lon2,lon2-lon,lon2-lon1)
	lat1 = lat2
	lon1 = lon2
	strlog = "%d,%12.8f,%12.8f,%s\r\n"%(gcount,lat2,lon2,msg.timestamp)
	gpsfile.write(strlog)
	
#解析GPS的NMEA0180数据格式。
def ongpsdata(strNMEA):
	#strNMEA=data.strip()
	#print strNMEA
	msg = pynmea2.parse(strNMEA)
	#print "Location:",msg.lat_dir,"-",msg.latitude,",",msg.lon_dir,"-",msg.longitude
	print '%02d°%02d′%07.4f″' % (msg.latitude, msg.latitude_minutes, msg.latitude_seconds),
	print '%02d°%02d′%07.4f″' % (msg.longitude, msg.longitude_minutes, msg.longitude_seconds),
	print msg.timestamp
	#gpscenter(msg.latitude_seconds,msg.longitude_seconds)
	gpscenterx(msg)
	#print "Satellite:%d",msg.num_sats
	#print "altitude:",msg.altitude
	#print "ongpsdata",strNMEA

#============================================
def tcpclient():
	global addr
	while True: 
		if IS_RUN == 0:
			break
		data = tcpClientSock.recv(1024)
		if not data: 
		    break 
		#print ">>",data.strip()
		ongpsdata(data.strip())

def tcpstart():
	t_asocket = threading.Thread(target=tcpclient,args=())
	t_asocket.setDaemon(True)
	t_asocket.start()

#============================================
def exeCMD(strCMD):
	if (strCMD.find("$")==0):	#主机命令。
		strResult = exeHost(strCMD)
		return strResult
	elif(strCMD.find("?")==0):	#主机命令。
		exeHost_help(strCMD)
	else:
		exeRemote(strCMD)	#发送到网络。
		#strResult = tcpClientSock.sendto(strCMD,ADDR)
		#return strResult

def exeRemote(strRemote):
	#tcpClientSock.send(strRemote+'\r\n')	#发送到网络。
	tcpClientSock.send(strRemote)	#发送到网络。
	
#Run CMD at host.	
#执行主机的操作。
def exeHost(strCMD):
	if (strCMD.upper()=="$LOADFILE") or (strCMD.upper()=="$LF"):
		exeHost_lua_upload()
	elif (strCMD.upper()=="$DOFILE") or (strCMD.upper()=="$DF"):
		exeHost_lua_dofile()
	elif (strCMD.upper()=="$LOADTEST"):
		lua_upload("./xlua/hello.lua","hello.lua")
	else:	
		print "Host CMD: ",strCMD
	return "HOSTCMD:",strCMD

#Get Help.
#获取帮助信息。
def exeHost_help(strCMD):
	if (strCMD.upper()=="?XCMD"):
		xcmd_xcon.xc_help.xcmd_list()
	else:
		print "Not find Help doc."
		#xc_help.base_list()
		
#============================================
#loadluafile into nodemcu.
def exeHost_lua_upload():
	luafilehost = raw_input('Input LUA file pathname:') 
	luafileremote = raw_input('Input Remote file name:') 
	lua_upload(luafilehost,luafileremote)

#run a lua file on remote nodemcu.
def exeHost_lua_dofile():
	luafilehost = raw_input('Run LUA file pathname:') 
	lua_dofile(luafilehost)

#============================================
#upload a lua file to remote nodemcu.
def lua_upload(luahost,luaremote):	
	print "Uploading:",luahost,",",luaremote
	print "=========================================="
	luafilehost = open(luahost,'r')
	strRemote = "file.open(\""+luaremote+"\",\"w\")"
	print strRemote
	strResult = exeRemote(strRemote)
	sleep(1)
	for  strlualine in  luafilehost: 
		strlualine = strlualine.strip('\n') 
		strlualine = strlualine.replace("\\","\\\\")
		strlualine = strlualine.replace("\"","\\\"")
		strlualine = "file.writeline(\'"+strlualine+"\')"
		print strlualine
		strLast = exeRemote(strlualine)
		sleep(1)
	strRemote = "file.flush()"
	print strRemote
	exeRemote(strRemote)
	sleep(2)
	strRemote = "file.close()"
	print strRemote
	exeRemote(strRemote)	
	luafilehost.close()
	print "===Upload LUA finished.===================="
	print ""

#run a lua file as dofile() in lua.
#将本地LUA文件在远端运行,通过逐行发送来进行。
def lua_dofile(luahost):	
	print "Remote Run:",luahost
	print "=========================================="
	luafilehost = open(luahost,'r')
	for  strlualine in  luafilehost: 
		print strlualine
		strLast = exeRemote(strlualine)
		sleep(1)
	luafilehost.close()
	print "===Run LUA at remote finished.============"
	print ""

#============================================
def processcmd():
	if (len(sys.argv)<=1):
		return
	for arg in sys.argv:
		print arg
	if sys.argv[1].upper()=="LFALL":
		print "Begin upload all LUA..."
		exeHost_lua_uploadall()
	exit()

def configip():
	if (len(sys.argv)<=1):
		return
	for arg in sys.argv:
		print arg
	print "Config remote IP:"
	HOST = sys.argv[1]
	
#============================================
def waitinput():
	while True: 
		xcmd = raw_input('') 
		if (xcmd.upper()=="EXIT"):
			IS_RUN = 0
			tcpClientSock.close()
			print "[xconsole for wifi] exited."
			exit()
		exeCMD(xcmd)

#============================================
if __name__ == "__main__":
	try: 
		gpsfile = open(gpsfilename,'w')
		configip()
		tcpstart()
		waitinput()
	except Exception as err:
		print err
	finally:  
		gpsfile.close()
		print("Goodbye!")
		exit()
		

